﻿using System;
using System.Collections.Generic;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using SdmxMl.Common;
using SdmxMl.Manager;
using SdmxMl.Structure;
using SdmxMl.GenericMetadata;
using SdmxMl.Pdf;
using SdmxMl.SanteSuisse;

namespace SilcQuest
{
    public class PdfQuest
    {
        #region Internal members

        protected Document document;
        protected SmManager sm;
        protected RefVarHelper varHelper;
        protected PdfQuestDetail pdfDetail;
        protected Artefact targetArtefact;

        protected MetadataSetType metaSet;
        protected MetadataStructureDefinitionType msd;
        protected ReportStructureType report;
        private int maxCodesInPdf;

        #endregion

        public PdfQuest(SmManager smMgr, int maxCodes)
        {
            sm = smMgr;
            maxCodesInPdf = maxCodes;

        }

        private void BindRequiredMetadata(string artefactFullId)
        {
            ArtefactRefTyped arType = new ArtefactRefTyped(SdmxArtefactType.MetadataSet, artefactFullId);
            metaSet = sm.GetArtefact(arType.Type, arType, true) as MetadataSetType;
            if (metaSet == null)
                throw new ApplicationException(string.Format("Unable to locate Metadataset: {0} ", artefactFullId));

            // Get MSD structure attached
            msd = sm.GetArtefact(SdmxArtefactType.MetadataStructureDefinitions, metaSet.MetadataStructureRef, true) as MetadataStructureDefinitionType;
            if (msd == null)
                throw new ApplicationException(string.Format("Unable to locate MSD associated to metaset: {0} ", metaSet.MetadataStructureRef.FullIdent));

            // Get Report to work with
            report = msd.ReportStructureList.LocateItem(metaSet.ReportRef);
            if (report == null)
                throw new ApplicationException(string.Format("Unknown Report ID:{0} in MSD: {1}", metaSet.ReportRef, metaSet.MetadataStructureRef.FullIdent));
        }

        public void Generate(string docPath, string artefactFullId, string langCd)
        {
            //Create PDF Document
            document = new Document(PageSize.A4);

            try
            {
                // Get metadataset to generate in PDF
                BindRequiredMetadata(artefactFullId);

                // Init document
                document.SetMargins(72, 72, 72, 72);
                document.SetMarginMirroring(true);

                // Create helper for codelist and concepts
                varHelper = new RefVarHelper(sm);
                pdfDetail = new PdfQuestDetail(document, langCd, PageSize.A4, varHelper);


                // we create a writer that listens to the document
                // and directs a PDF-stream to a file
                PdfWriter docWriter = PdfWriter.GetInstance(document, new FileStream(docPath, FileMode.Create));
                PdfWriterEvents writerEvent = new PdfWriterEvents("Test");
                docWriter.PageEvent = writerEvent;
                PdfWriterPage page = new PdfWriterPage(metaSet.Name.GetForLanguage(langCd));
                docWriter.PageEvent = page;

                // open the document
                document.Open();

                FontSelector selector = new FontSelector();
                selector.AddFont(FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9));


                // MSD Attributes
                int row = 0;
                foreach (AttributeValueSetType att in metaSet.AttributeValueSetList)
                {
                    CatiSilcQuestion question = new CatiSilcQuestion(varHelper, att, langCd);
                    question.MaxCodes = maxCodesInPdf;

                    document.Add(pdfDetail.PrepareQuestionHeader(question, metaSet.ReportRef == "R_SILC_TECH"));
                    document.Add(pdfDetail.PrepareQuestionTexts(question));
                    document.Add(pdfDetail.PrepareSubQuest(question));
                    document.Add(new Paragraph(new Chunk(" ")));
                    document.Add(pdfDetail.PrepareCodeAndQuality(question));
                    document.Add(new Paragraph(new Chunk(" ")));
                    document.Add(new Paragraph(new Chunk(" ")));

                    if (++row % 2 == 0)
                        document.NewPage();
                }


            }
            finally
            {
                if (document != null && document.IsOpen())
                    document.Close();
            }
        }
    }
}
